package cn.com.easy.utils;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.IOUtils;

import com.google.common.collect.Lists;

/**
 * 此linux之命令工具类矣
 * 
 * @author nibili 2018年10月11日
 * 
 */
public class LinuxCommondUtils {

	/**
	 * ps命令
	 * 
	 * @param gerpString
	 * @return
	 * @throws Exception
	 * @auth nibili 2018年10月17日 196888813@qq.com
	 */
	public static List<String> executePsCommond(String gerpString) throws Exception {
		Process p1 = Runtime.getRuntime().exec(new String[] { "ps", "-ef" });
		InputStream input = p1.getInputStream();
		Process p2 = Runtime.getRuntime().exec(new String[] { "grep", "epoch" });
		OutputStream output = p2.getOutputStream();
		IOUtils.copy(input, output);
		output.close(); // signals grep to finish
		List<String> lines = IOUtils.readLines(p2.getInputStream(), "UTF-8");
		return lines;
	}

	/**
	 * 执行命令并返回字符串集合
	 * 
	 * @param command
	 * @return
	 * @throws Exception
	 * @auth nibili 2018年10月11日 196888813@qq.com
	 */
	public static String executeCommandFileAndReturnString(String command) throws Exception {
		StringBuilder stringBuilder = new StringBuilder();
		List<LineNumberReader> inputs = LinuxCommondUtils.executeCommandFile(command);
		String line;
		for (LineNumberReader input : inputs) {
			while ((line = input.readLine()) != null) {
				stringBuilder.append(line + "\r\n");
			}
		}
		return stringBuilder.toString();
	}

	/**
	 * 执行命令并返回字符串集合
	 * 
	 * @param command
	 * @return
	 * @throws Exception
	 * @auth nibili 2018年10月11日 196888813@qq.com
	 */
	public static List<String> executeCommandFileAndReturnStringList(String command) throws Exception {
		List<String> list = Lists.newArrayList();
		List<LineNumberReader> inputs = LinuxCommondUtils.executeCommandFile(command);
		String line;
		for (LineNumberReader input : inputs) {
			while ((line = input.readLine()) != null) {
				list.add(line);
			}
		}
		return list;
	}

	/**
	 * 执行命令
	 * 
	 * @param command
	 * @return
	 * @throws Exception
	 * @auth nibili 2018年10月11日 196888813@qq.com
	 */
	public static List<LineNumberReader> executeCommandFile(String command) throws Exception {
		if (command.contains("rm ") || command.contains("mv ")) {
			throw new Exception("命令不合法");
		}
		Process process = Runtime.getRuntime().exec(command);
		LineNumberReader errorStreamReader = new LineNumberReader(new InputStreamReader(process.getErrorStream()));
		LineNumberReader input = new LineNumberReader(new InputStreamReader(process.getInputStream()));
		List<LineNumberReader> readers = new ArrayList<LineNumberReader>();
		readers.add(input);
		readers.add(errorStreamReader);
		return readers;
	}
}
